import {showToast, formatNumber, navigateTo} from '../../../utils/util'
import request from '../../../utils/request.js'
import WxValidate from '../../../lib/WxValidate.js'
const accountInfo = wx.getAccountInfoSync()
const env = accountInfo.miniProgram.envVersion

let date = new Date()
let currentHours = date.getHours()
let currentMinute = date.getMinutes()
const chooseLocation = requirePlugin('chooseLocation')
const reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g
Page({

  /**
   * 页面的初始数据
   */
  data: {
    remarkMax: 200,
    currentWordNumber: 0,
    currentTabStr: "",
    currentTab: 0,
    tabs: ['出院预约', '入院预约'],
    startDate: "请选择",
    multiArray: [['今天', '明天'], [0, 1, 2, 3, 4, 5, 6], [0, 10, 20]],
    multiIndex: [0, 0, 0],
    hosPlace: '',
    from: '',
    to: '',
    mobile: '',
    remark: '',
    needCPAP: false,
    isStretcherUp: false,
    isAgree: false,
    localtion: null,
    id: null,
    isEdit: true,
    status: 0,
    placeArray: []
  },

  // 加载医院地点列表
  loadPlaces() {
    request.getRequest('/params/params', {
      paramType: 'placeSetting'
    }).then(res => {
      res.code === 1 && this.setData({
        placeArray: res.data
      })
    })
  },

  //点击切换
  tabChangeHandler: function (event) {
    let idx = event.detail.idx
    if (this.data.currentTab === idx) {
      return false;
    } else {
      this.setData({
        currentTab: idx
      }, function () {

      })
    }
  },

  placeChange(e) {
    this.setData({
      hosPlace: e.detail.value
    })
  },

  needCPAPChange(evt) {
    this.setData({
      needCPAP: evt.detail.value
    })
  },

  stretcherUpChange(evt) {
    this.setData({
      isStretcherUp: evt.detail.value
    })
  },

  checkboxChange(e) {
    this.setData({
      isAgree: e.detail.value.length > 0
    })
  },

  goToMap() {
    const key = 'XRVBZ-TBU3V-NDZPU-U2224-4QTMQ-KJFYO' //使用在腾讯位置服务申请的key
    const referer = '医大一服务-地图定位' //调用插件的app的名称
    let location = ''
    wx.getLocation({
      success: function (res) {
        let lat = res.latitude
        let lon = res.longitude

        location = JSON.stringify({
          latitude: lat,
          longitude: lon
        })
      },
    })

    wx.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location=' + location
    })
  },

  showAgreement() {
    wx.navigateTo({
      url: './agreement/agreement',
    })
  },

  /***验证表单字段 */
  initValidate: function () {
    const rules = {
      applyName: {
        required: true,
        noEmoji: true,
      },
      from: {
        required: true
      },
      to: {
        required: true
      },
      mobile: {
        required: true,
        tel: true
      },
    }
    const messages = {
      applyName: {
        required: '请填写申请人姓名',
        noEmoji: '申请人姓名不能输入表情', 
      },
      from: {
        required: '出发地不能为空',
      },
      to: {
        required: '目的地不能为空',
      },
      mobile: {
        required: '请填写手机号',
        tel: '请填写正确的手机号'
      },
    }
    this.WxValidate = new WxValidate(rules, messages)
  },

  formSubmit(e) {
    let _that = this;
    let formData = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(formData)) {
      const error = this.WxValidate.errorList[0]
      showToast('text', error.msg)
      return false
    }
    if (this.data.startDate === '请选择') {
      showToast('text', '请选择用车时间')
      return false
    }
    if (!this.data.isAgree) {
      showToast('text', '请勾选用户协议')
      return false
    }
    wx.showLoading()

    let from = this.data.currentTab === 0 ? this.data.placeArray[this.data.hosPlace].paramValue : formData.from
    let to = this.data.currentTab === 0 ? formData.to : this.data.placeArray[this.data.hosPlace].paramValue
    let mobile = formData.mobile
    let remark = formData.remark
    let applyName = formData.applyName
    let online = (env !== 'develop') ? 1 : 0;
    let params = {
      applyName: applyName,
      ambulanceType: this.data.currentTab,
      fromAddress: from,
      toAddress: to,
      fromCoordinate: this.data.currentTab === 1 ? this.data.location: undefined,
      toCoordinate: this.data.currentTab === 0 ? this.data.location: undefined,
      applyTime: this.data.startDate + ':00',
      mobile,
      needRespirator: this.data.needCPAP,
      needStretcher: this.data.isStretcherUp,
      online: online,
      personnelRemark: remark
    }
    if(null != this.data.id){
      let id = this.data.id;
      request.getRequest('/sjzydy/ambulance/' + id, {}).then(res => {
          if(res.code === 1 && null != res.data){
            let ambulance = res.data;
            if(ambulance.status > 0){
                wx.hideLoading()
                showToast('error', '该预约记录已不可修改', { isMask: true, duration: 2000 })
                setTimeout(() => {
                    wx.navigateTo({
                        url: "/pages/me/ambulanceRecord/ambulanceRecord"
                    })
                }, 2000)
                return;
            }
            else{
                params.id = id;
                _that.saveData(params,'预约记录修改成功', '预约记录修改失败');
            }
          }
          else{
              showToast('error', '预约记录信息错误', { isMask: true, duration: 2000 })
              setTimeout(() => {
                  wx.navigateBack()
              }, 2000)
          }
      });
      console.log("this.data.status", this.data.status);
    }
    else{
        this.saveData(params,'救护车预约成功', '救护车预约失败');
    }

  },
  saveData(params, successMsg, errorMsg){
      let isAdd = (null == params.id)
      let url = isAdd ? "/pages/home/index/index" : "/pages/me/ambulanceRecord/ambulanceRecord" ;
      request.postRequest('/sjzydy/ambulance/save', params).then(addRes => {
          let msg = addRes.code === 1 ? successMsg : errorMsg
          let type = addRes.code === 1 ? 'success' : 'error'
          wx.hideLoading();
          showToast(type, msg, { isMask: true, duration: 2000 })
          setTimeout(() => {
            isAdd ? wx.switchTab({url: url}) : wx.navigateTo({url: url});
          }, 2000)
      }).catch(err => {
          wx.hideLoading();
          showToast('error', errorMsg, { isMask: true, duration: 2000 })
          setTimeout(() => {
            isAdd ? wx.switchTab({url: url}) : wx.navigateTo({url: url});
          }, 2000)
      })
  },

    /****限制字数与计算 */
    getValueLength: function (e) {
        this.inputVal(e);
        let value = e.detail.value
        let len = parseInt(value.length)
        //最多字数限制
        if (len > this.data.remarkMax) return;
        this.setData({
            currentWordNumber: len //当前字数
        })
    },

  pickerTap: function () {
    date = new Date()

    let monthDay = ['今天', '明天']
    let hours = []
    let minute = []

    currentHours = date.getHours()
    currentMinute = date.getMinutes()

    // 年-月-日
    for (let i = 2; i <= 29; i++) {
      let date1 = new Date(date)
      date1.setDate(date.getDate() + i)
      let md = date1.getFullYear() + "-" + formatNumber(date1.getMonth() + 1) + "-" + formatNumber(date1.getDate())
      monthDay.push(md)
    }

    let data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    }

    if (data.multiIndex[0] === 0) {
      if (data.multiIndex[1] === 0) {
        this.loadData(hours, minute)
      } else {
        this.loadMinute(hours, minute)
      }
    } else {
      this.loadHoursMinute(hours, minute)
    }

    data.multiArray[0] = monthDay
    data.multiArray[1] = hours
    data.multiArray[2] = minute

    this.setData(data)
  },

  bindMultiPickerColumnChange: function (e) {
    date = new Date()
    let that = this

    let monthDay = ['今天', '明天']
    let hours = []
    let minute = []

    currentHours = date.getHours()
    currentMinute = date.getMinutes()

    let data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    }
    // 把选择的对应值赋值给 multiIndex
    data.multiIndex[e.detail.column] = e.detail.value

    // 然后再判断当前改变的是哪一列,如果是第1列改变
    if (e.detail.column === 0) {
      // 如果第一列滚动到第一行
      if (e.detail.value === 0) {
        that.loadData(hours, minute)
      } else {
        that.loadHoursMinute(hours, minute)
      }

      data.multiIndex[1] = 0
      data.multiIndex[2] = 0

      // 如果是第2列改变
    } else if (e.detail.column === 1) {
      // 如果第一列为今天
      if (data.multiIndex[0] === 0) {
        if (e.detail.value === 0) {
          that.loadData(hours, minute)
        } else {
          that.loadMinute(hours, minute)
        }
        // 第一列不为今天
      } else {
        that.loadHoursMinute(hours, minute)
      }
      data.multiIndex[2] = 0

      // 如果是第3列改变
    } else {
      // 如果第一列为'今天'
      if (data.multiIndex[0] === 0) {
        // 如果第一列为 '今天'并且第二列为当前时间
        if (data.multiIndex[1] === 0) {
          that.loadData(hours, minute)
        } else {
          that.loadMinute(hours, minute)
        }
      } else {
        that.loadHoursMinute(hours, minute)
      }
    }
    data.multiArray[1] = hours
    data.multiArray[2] = minute
    this.setData(data)
  },

  loadData: function (hours, minute) {
    let minuteIndex
    if (currentMinute > 0 && currentMinute <= 10) {
      minuteIndex = 10
    } else if (currentMinute > 10 && currentMinute <= 20) {
      minuteIndex = 20
    } else if (currentMinute > 20 && currentMinute <= 30) {
      minuteIndex = 30
    } else if (currentMinute > 30 && currentMinute <= 40) {
      minuteIndex = 40
    } else if (currentMinute > 40 && currentMinute <= 50) {
      minuteIndex = 50
    } else {
      minuteIndex = 60
    }

    if (minuteIndex == 60) {
      // 时
      for (let i = currentHours + 1; i < 24; i++) {
        hours.push(formatNumber(i))
      }
      // 分
      for (let i = 0; i < 60; i += 10) {
        minute.push(formatNumber(i))
      }
    } else {
      // 时
      for (let i = currentHours; i < 24; i++) {
        hours.push(formatNumber(i))
      }
      // 分
      for (let i = minuteIndex; i < 60; i += 10) {
        minute.push(formatNumber(i))
      }
    }
  },

  loadHoursMinute: function (hours, minute) {
    // 时
    for (let i = 0; i < 24; i++) {
      hours.push(formatNumber(i))
    }
    // 分
    for (let i = 0; i < 60; i += 10) {
      minute.push(formatNumber(i))
    }
  },

  loadMinute: function (hours, minute) {
    let minuteIndex
    if (currentMinute > 0 && currentMinute <= 10) {
      minuteIndex = 10
    } else if (currentMinute > 10 && currentMinute <= 20) {
      minuteIndex = 20
    } else if (currentMinute > 20 && currentMinute <= 30) {
      minuteIndex = 30
    } else if (currentMinute > 30 && currentMinute <= 40) {
      minuteIndex = 40
    } else if (currentMinute > 40 && currentMinute <= 50) {
      minuteIndex = 50
    } else {
      minuteIndex = 60
    }

    if (minuteIndex == 60) {
      // 时
      for (let i = currentHours + 1; i < 24; i++) {
        hours.push(formatNumber(i))
      }
    } else {
      // 时
      for (let i = currentHours; i < 24; i++) {
        hours.push(formatNumber(i))
      }
    }
    // 分
    for (let i = 0; i < 60; i += 10) {
      minute.push(formatNumber(i))
    }
  },

  bindStartMultiPickerChange: function (e) {
    let that = this
    let monthDay = that.data.multiArray[0][e.detail.value[0]]
    let hours = that.data.multiArray[1][e.detail.value[1]]
    let minute = that.data.multiArray[2][e.detail.value[2]]

    if (monthDay === "今天") {
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      monthDay = year + "-" + month + "-" + day
    } else if (monthDay === "明天") {
      let date1 = new Date(date)
      date1.setDate(date.getDate() + 1)
      monthDay = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate()
    }
    // else {
    //   let month = monthDay.split("-")[0] // 返回月
    //   let day = monthDay.split("-")[1] // 返回日
    //   monthDay = month + "月" + day + "日"
    // }

    let startDate = monthDay + " " + hours + ":" + minute
    that.setData({
      startDate: startDate
    })
  },

    getInfo(id){
      let _that = this;
      request.getRequest('/sjzydy/ambulance/' + id, {}).then(res => {
        if(res.code === 1 && null != res.data){
          let ambulanceInfo = res.data;
          console.log("ambulanceInfo", ambulanceInfo);
          console.log("data begin", _that.data);
          _that.setData({
              status: ambulanceInfo.status,
              applyName: ambulanceInfo.applyName,
              currentTab: ambulanceInfo.ambulanceType,
              startDate: ambulanceInfo.applyTime,
              mobile: ambulanceInfo.mobile,
              needCPAP: ambulanceInfo.needRespirator,
              isStretcherUp: ambulanceInfo.needStretcher,
              remark: ambulanceInfo.personnelRemark,
              isAgree: true
          });
          if(ambulanceInfo.status > 0){
              _that.setData({
                  isEdit: false
              });
          }
          let placeArray = _that.data.placeArray;
          let address = '';
          if(ambulanceInfo.ambulanceType == 0){
            address = ambulanceInfo.fromAddress;
            _that.setData({
                to: ambulanceInfo.toAddress,
                toCoordinate: ambulanceInfo.toCoordinate,
                currentTabStr: "出院预约"
            });
          }
          else {
            address = ambulanceInfo.toAddress;
            _that.setData({
                from: ambulanceInfo.fromAddress,
                fromCoordinate: ambulanceInfo.fromCoordinate,
                currentTabStr: "入院预约"
            });
          }
          let key = 0;
          let place = placeArray.filter((item, index)=>{
            let paramValue = item.paramValue;
            if(paramValue.indexOf(address) != -1){
              key = index;
              return index;
            }
          });
          _that.setData({
              hosPlace: key
          });


        }
      }).catch(res=>{

      });
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadPlaces();
    this.initValidate();
    if(null != options.id){
        this.setData({
            id: options.id
        });
        this.getInfo(this.data.id);
    }
    console.log("isEdit", this.data.isEdit);
  },
  onShow: function() {
    const location = chooseLocation.getLocation()
      if(location != null) {
        if (this.data.currentTab === 0) {
            this.setData({
                to: location.name,
                location: location.latitude + ',' + location.longitude
            })
        } else {
            this.setData({
                from: location.name,
                location: location.latitude + ',' + location.longitude
            })
        }
      }
  },
  onUnload: function() {
    chooseLocation.setLocation(null)
  },

  /**
   * 验证表情
   * @param str
   * @returns {{val: *, index: ({groups: {}}|RegExpExecArray)}}
   */
  regStrFn: function(str){
      let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g ,
          indexArr = reg.exec(str);
      if(str.match(reg)) {
          str = str.replace(reg, '');
          showToast('error', '不可输入表情', { isMask: true, duration: 2000 })
      }
      let obj = { val: str, index: indexArr}
      return obj
  },

  inputVal: function (e) {
      let name = e.target.dataset.name
      let val = e.detail.value,
          pos = e.detail.cursor;
      let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g
      if (!reg.test(val)){
          return
      }
      let obj = this.regStrFn(val)

      if (pos != -1 && obj.index) {
          // 计算光标的位置
          pos = obj.index.index
      }
      return {
          value: obj.val,
          cursor: pos
      }
  }
})
